import { Controller, Req, Res, Get, Render, Param, Query, StreamableFile } from '@nestjs/common';
import { Request, Response } from 'express';
import { AppService } from './app.service';
import { createReadStream } from 'fs';
const mime = require('mime');

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('helloworld')
  @Render('helloworld')
  getHello() {
    return { message: this.appService.getHello() };
  }

  @Get('/')
  @Render('index')
  index(@Req() req: Request, @Res() res: Response) {
  }

  @Get('/ls-lR')
  getListByRecursion(@Query('path') filename: string) {
    filename = typeof filename !== 'undefined' ? filename : '/';
    let r = {success: true, value: undefined, message: ''};
    r.value = this.appService.getListByRecursion(filename);
    return r;
  }
  
  @Get('/ls-l')
  getListByDetail(@Query('path') filename: string) {
    filename = typeof filename !== 'undefined' ? filename : '/';
    let r = {success: true, value: undefined, message: ''};
    r.value = this.appService.getListByDetail(filename)
		    .filter(item => !item["fn"].startsWith("."));
    return r;
  }

  @Get('/file')
  getFile(@Req() req: Request, @Res({ passthrough: true }) res: Response,
	  @Query('fn') filename: string) {
    try {
      const rs = this.appService.getFile(filename);
      // rs.pipe(res);
      res.writeHead(200, {
	'Content-Type': `${mime.getType(filename)}; charset=utf8`,
      });
      return new StreamableFile(rs);
    } catch (e) {
      return e;
    }
  }
}
